package controller;


import javax.swing.JFileChooser;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

import model.MP3FileMutableTreeNode;

import view.GUI;
import view.DirectoryTree;

/**
 * The TreeFileTreeSelectionListener provides the event handling functions for the JTree.
 * 
 *
 */
public class TreeFileTreeSelectionListener implements TreeSelectionListener {

	//gui as instance variable to redraw it
	private GUI superview;
	private DirectoryTree tree;
	private boolean readyToSelect;
	
	//constructor of the selectionListener with possibility to add its superview and its tree as instancevariable
	public TreeFileTreeSelectionListener(DirectoryTree tree,Object superview){
		this.superview = (GUI)superview;
		this.tree = tree;
		readyToSelect = true;
	}
	
	/**
	 * valueChanged listener to handle the selection of a particular node in our tree
	 */
	@Override
    public void valueChanged(TreeSelectionEvent e) {
		//get the selected node as default node structure
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();

        //return if nothing is selected 
        if (node == null) 
        	return;	
        		
    	if (node instanceof MP3FileMutableTreeNode) {
    		MP3FileMutableTreeNode mp3Node = (MP3FileMutableTreeNode) node;
			if (mp3Node.getMP3File() != null) {
				//redraw gui
				this.superview.redrawGUIWithNewMP3Node(mp3Node);
				readyToSelect = true;
			}
		}
		if(node.getUserObject().equals("Verzeichnis aussuchen") && readyToSelect) {
    		
    		//create a file chooser to let the user select a new root directory
        	JFileChooser fileChooser = new JFileChooser();
        	fileChooser.setDialogTitle("choose the root directory of your MP3 collection");
        	fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              
         	//when the filechooser has finished selection, get response:
            if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            	//the user selected the folder with title "directoryString"
            	String directoryString = fileChooser.getSelectedFile().toString();
            	
            	//refresh the file tree in gui
            	readyToSelect = false;
            	this.tree.addNodesFromDirectory(directoryString);
            }
		}
		readyToSelect = true;
    }
}
